<?php

class ome_ctl_admin_api extends base_controller
{

    var $name = "订单中心";
    var $workground = "order_center";
    var $order_type = 'all';

    function api_function_test()
    {

        $now = time();
        $begintime = date("m-d H:i");
        $limit1_time = $now -18;
        // $limit1_time = $now;
        $limit2_time = $now -86400;
        $oOrders = app::get('ome')->model('orders');
        $oOrderItemMdl = app::get('ome')->model('order_items');
        $oOrdersObjMdl = app::get('ome')->model('order_objects');
        $orderReplace=kernel::single('ome_order_replace');
        $order_list = $oOrders->getlist('pay_status,order_bn,order_id,is_replace,shop_id,is_cod,status',array('order_confirm_filter' => '(op_id IS NULL AND group_id IS NULL AND (is_cod=\'true\' or pay_status in (\'1\',\'4\',\'5\')))', 'status' => 'active', 'ship_status' => '0','download_time|lthan'=>$limit1_time,'download_time|than'=>$limit2_time, 'f_ship_status' => '0', 'confirm' => 'N', 'abnormal' => 'false', 'is_auto' => 'false', 'is_fail' => 'false'));
        
        if(empty($order_list)) return false;

        foreach ($order_list as $k => $v)
        {
            //只有没有替换的订单  才进行替换
            if($v['is_replace']=='false')
            {
                try
                {
                    //先获取数据   $sdf a
                    // 获取该所有订单明细
                    $orderItems = $oOrderItemMdl ->getlist('*',array('order_id'=>$v['order_id']));
                    $items_data=array();
                    $pre_datas=array();
                    foreach($orderItems as $item) 
                    {
                        $items_data[$item['item_id']]['rep_bm_id'] = $item['product_id'];
                        $items_data[$item['item_id']]['rep_material_bn'] = $item['bn'];
                        $items_data[$item['item_id']]['repalce_num'] = $item['nums'];
                        $items_data[$item['item_id']]['ti_num'] = $item['nums'];
                        $items_data[$item['item_id']]['rep_material_name'] = $item['name'];
                        $items_data[$item['item_id']]['item_id'] = $item['item_id'];
                        $items_data[$item['item_id']]['obj_id'] = $item['obj_id'];
                        $items_data[$item['item_id']]['price'] = $item['price'];
                        $items_data[$item['item_id']]['pmt_price'] = $item['pmt_price'] / $item['nums'];
                        $items_data[$item['item_id']]['part_mjz_discount'] = $item['part_mjz_discount'] / $item['nums'];

                        $pre_datas[$item['product_id']]['nums'] = $item['nums'];
                        $pre_datas[$item['product_id']]['item_id'] = $item['item_id'];
                        $pre_datas[$item['product_id']]['obj_id'] = $item['obj_id'];
                    }
                    //获取该订单  最终所替代的明细   比对之前的明细  再进行处理
                    $data=$orderReplace->dealdata($items_data,$v['shop_id']);

                    $data2=array();
                    foreach($data as $kk=>$vv)
                    {
                        //说明替换物料有原物料中的一种  在
                        if($pre_datas[$vv['rep_bm_id']])
                        {
                            //如果 最终明细有一个原物料  且数量相同 则说明改 明细不用修改状态  改最终物料不需要重新插入
                            if($vv['repalce_num']==$pre_datas[$vv['rep_bm_id']]['nums'] )
                            {
                                //add by ldward 20180830 如果替换后的物料同原明细有相同切数量相同，则累加数量、实付金额、销售价格
                                if(empty($vv['item_id']))
                                {
                                    //如果item_id为空，则是替代物料，替代物料为原物料切且数量相同，一样添加到明细中
                                    
                                    $data2[]=$vv;
                                }
                                $pre_datas[$vv['rep_bm_id']]['is_replace']='false';
                                continue;
                            }else{
                                //有原物料  但是数据不一致  该最终明细 可以插入新的明细
                                $data2[]=$vv;
                            }
                        }else{
                            //最终物料  在原物料没有  则说明  是替换的 可以插入新的明细
                            $data2[]=$vv;
                        }
                    }
                    //如果新插入的  数组 为空  说明该订单不需要替换
                    if(!empty($data2))
                    {
                        error_log(date('Y-m-d H:i:s').'['.$v['order_id'].']'.var_export($data2, true), 3, PUBLIC_DIR.'/autoreplace'.date('Y-m-d').'.log');
                        
                        //循环插入新数组
                        kernel::database()->beginTransaction();
                        foreach($data2 as $newk=>$newv)
                        {
                            $orderReplace->createObjectItems_new($newv,$v['order_id']);
                        }
                        //循环修改 原来订单明细的状态
                        foreach($pre_datas as $key2 =>$vlaue2)
                        {
                            if($vlaue2['is_replace']=='false') continue;
                            $oOrderItemMdl = app::get('ome')->model('order_items');
                            $oOrdersObjMdl = app::get('ome')->model('order_objects');
                            $oOrderItemMdl ->update(array('delete'=>'true'),array('item_id' => $vlaue2['item_id']));
                            $oOrdersObjMdl ->update(array('delete'=>'true'),array('obj_id' => $vlaue2['obj_id']));
                            $oOrders ->update(array('is_replace'=>'true','replaced'=>'true'),array('order_id' => $v['order_id']));
                            $orderItems_rep = $oOrderItemMdl ->getlist('*',array('item_id'=>$vlaue2['item_id']));
                            $itemRepMdl = app::get('ome')->model('order_itemsRep');
                            $itemRepMdl->save($orderItems_rep[0]);
                        }
                        kernel::database()->commit();
                    }
                    //查询是否有相同的物料行
                    //add by ldward 因过数价格取价异常，则修改源头，如果存在相同料品（普通+普通、普通+促销），则进行平均
                    $db=kernel::database();
                    $sql="SELECT * from (
                                select order_id,bn,ROUND(sum(divide_order_fee)/sum(nums),4) divide_order_fee,count(bn) _c
                                from sdb_ome_order_items where order_id=".$v['order_id']." and `delete`='false' group by order_id,bn
                                )t where t._c>1";
                    $recopydata = $db->select($sql);
                    if(!empty($recopydata))
                    {
                        foreach ($recopydata as $key => $value) 
                        {
                            $db->exec("update sdb_ome_order_items set divide_order_fee=nums*".$value['divide_order_fee']." where order_id=".$v['order_id']." and bn='".$value['bn']."'");   
                        }
                    }


                }catch (Exception $e)
                {
                    kernel::database()->rollback();
                    $msg=$e->getMessage();
                    error_log(var_export(date('Y-m-d H:i:s') . 'replace-----' . $msg,true)."\n\t",3,PUBLIC_DIR."/replace_" . date('Y-m-d').".log");
                    //如果报错 回滚
                    continue;
                }
            }

            //error_log(var_export(222222,true)."\n\t",3,PUBLIC_DIR."/323333333333333.log");
            if(($v['pay_status'] == '1' || $v['is_cod'] == 'true') && $v['status'] == 'active')
            {
                $result = kernel::single('ome_order')->auto_order_combine($v['order_id']);
                error_log(var_export($v['order_id'],true)."\n\t",3,PUBLIC_DIR."/order_id_" . date('Y-m-d').".log");
            }

        }






    }
    function api_test()
    {

        $obj_regions_op = kernel::single('eccommon_regions_operation');
        $area =  $obj_regions_op->getRegionById();
        foreach ($area as $key => $value) {
            $province[] = $value['local_name'];
        }
        if(!in_array('四川',$province)){
            $msg = '省份填写不正确，请正确填写!（不带“省”）';

        }

        $city =  $obj_regions_op->getRegionByProvince('四川');

        if(!in_array('内江市',$city)){
            $msg = '城市填写不正确，请正确填写!';

        } 
        $county =  $obj_regions_op->getRegionByCity('四川','内江市');

        if(!in_array('东兴区',$county)){
            $msg = '城市填写不正确，请正确填写!';

        }
        header('Content-Type:text/html; charset=utf-8');
        print_r((($county)));
        print_r((($msg)));
    }
    function api_demo()
    {


        $url = "http://172.23.3.176/index.php?app=ome&ctl=admin_api&act=api_import";

        $post_data = array(
            0 => array(//一条订单信息
                'member_id' => '1', //购买人 默认  admin
                'address_id' => 'mainland:北京/北京市/东城区:3',
                'consignee' => array(
                    'area' => 'mainland:北京/北京市/东城区:3',
                    'addr' => '收货地址',
                    'name' => '收货人',
                    'zip' => '邮编',
                    'mobile' => '13800138000',
                    'telephone' => '0758-2222222',
                    'email' => '',
                ),
                'shop_id' => 'T079', //店铺ID
                'goods' => array(
                    0 => array(
                        'bn' => 'BY4080G1204', //商品编号
                        'num' => 2, //数量
                        'price' => 231, //销售金额
                    ),
                ),
                'is_cod' => false,
                'is_tax' => false,
                'branch_id' => '',
                'customer_memo' => '',
                'cost_shipping' => '',
                'tax_title' => '',
                'disc' => '',
                'discount' => '',
                'relate_order_bn' => 'LD'.time(),
                'order_memo' => '',
            ),

        );
        $post_data = array(
            "api_data" => json_encode($post_data),
            '_token' => md5('ax_ome_admin_api' . date('Y-m-d'))
        );

        if ($_GET['type'] == 'status') {

            $url = 'http://172.23.3.176/index.php?app=ome&ctl=admin_api&act=order_status';
            $post_data = array(
                'shop_id' => '80042238'
            , 'order_bn' => 'YJDF_LM2016091014515810152531'
            );
            $post_data = array(
                "api_data" => json_encode($post_data),
                '_token' => md5('ax_ome_admin_api' . date('Y-m-d'))
            );
        }
        if ($_GET['type'] == 'dead') {

            $url = 'http://172.23.3.176/index.php?app=ome&ctl=admin_api&act=order_dead';
            $post_data = array(
                'shop_id' => '80042238'
            , 'order_bn' => '111'
            );
            $post_data = array(
                "api_data" => json_encode($post_data),
                '_token' => md5('ax_ome_admin_api' . date('Y-m-d'))
            );
        }

        if ($_GET['type'] == 'mater') {

            $url = 'http://172.23.3.176/index.php?app=ome&ctl=admin_api&act=material_add';
            $post_data = array(
                0 => array(
                    'material_name' => '物料名称003' //物料名
                , 'goods_type' => '1' //物料类型 1=通用商品类型
                , 'material_bn' => 'bn003' // 编号
                , 'material_specification' => '件' //规格
                , 'material_code' => 'code003' //条码
                , 'brand' => '2' //品牌 1=璞竹 ； 2=理文
                , 'serial_number' => true //是否启用唯一码
                , 'special_setting' => '4' // 特殊扫码配置 3 配置 ； 4 关闭
                , 'visibled' => '1' // 是否可售 1 可售 ； 2 停售
                , 'first_num' => '1' // 特殊扫码配置 默认 1
                , 'last_num' => '' // 特殊扫码配置 默认 空
                , 'type' => '1' //物料属性 1 普通 ； 2 组合
                , 'use_expire' => '2' //是否启用保质期监控 1 开启 2 关闭
                , 'cost' => '1' //成本价
                , 'retail_price' => '2' //售价
                , 'weight' => '3' //重量
                , 'unit' => '包' //包装单位
                ),
                1 => array(
                    'material_name' => '物料名称002'
                , 'goods_type' => '1'
                , 'material_bn' => 'bn002'
                , 'material_specification' => '件'
                , 'material_code' => 'code002'
                , 'brand' => '2'
                , 'serial_number' => true
                , 'special_setting' => '4'
                , 'visibled' => '1'
                , 'first_num' => '1'
                , 'last_num' => 'xxxxx'
                , 'type' => '1'
                , 'use_expire' => '2'
                , 'cost' => '1'
                , 'retail_price' => '2'
                , 'weight' => '3'
                , 'unit' => '包'
                ),
            );
            $post_data = array(
                "api_data" => json_encode($post_data),
                '_token' => md5('ax_ome_admin_api' . date('Y-m-d'))
            );
        }

        if ($_GET['type'] == 'fahuo') {
            $url = 'http://172.23.3.176/index.php?app=ome&ctl=admin_api&act=PDATOOMSship';
            $post_data = array(
                "api_data" => '11',
                "carno" => '粤011',
                "weight" => '5000',
                '_token' => md5('ax_ome_admin_api' . date('Y-m-d'))
            );
        }


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        //打印获得的数据
        header('Content-Type:text/html; charset=utf-8');
        print_r((($output)));
    }


    function testBI(){
        error_log(date('Y-m-d H:i:s').'获取数据/'.var_export(array($_POST,$_GET),true),3,DATA_DIR.'/testBI.log');
        $data=array_merge($_POST,$_GET);
        //$data['List']=array('name'=>'1');
        $this->api_view(true,$data);
    }

    function api_view($type, $msg)
    {
        $res = array(
            'msg' => $msg,
            'succeed' => $type,
        );
        print_r((json_encode($res)));
        exit();
    }

    /**
     *
     * @param type $token_key
     * @param type $token_param
     * @param type $value
     * @param type $type
     */
    function _token($token_key, $token_param, $value, $type = 1)
    {

        if ($type == 1) {
            $_token_value = md5($token_key . '_' . $token_param . date('Y-m-d'));
        }
        if ($value == $_token_value) {
            return true;
        } else {
            return false;
        }
    }

    //导入
    function api_import()
    {
        $this->begin();
//        测试数据
        $datas = $_POST['api_data'];
        $datas = json_decode($datas, true);
        error_log(date('Y-m-d H:i:s').'发送数据/'.var_export($datas,true),3,DATA_DIR.'/api_orders_'.date('Y-m-d').'.log');
        $salesMLib = kernel::single('material_sales_material');
        $oObj = $this->app->model("orders");

        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, 'token不正确');
        }
        if (!$datas) {
            $this->api_view(false, '订单不能为空');
        }

        foreach ($datas as $key => $val) {

            if (!$val) {
                $this->api_view(false, '订单明细不能为空');
            }
            $is_code = false;
            $weight = 0;
            $item_cost = 0;
            $import_data = $val;
            $post = $import_data;
            $post['consignee']['r_time'] = '任意日期 任意时间段';
            $post['consignee']['area'] = $post['address_id'];

            $post['member_id'] = $post['member_id'];
            if (!$post['member_id'])
                $this->api_view(false, '请选择会员');
            if (!$post['cost_shipping'])
                $post['cost_shipping'] = 0;
            if (!$post['discount'])
                $post['discount'] = 0;

            $consignee = $post['consignee'];
            if ($consignee) {
                if (!$consignee['name']) {
                    $this->api_view(false, '请填写收件人');
                }
                if (!$consignee['area']) {
                    $this->api_view(false, '请填写配送三级区域');
                }
                if (!$consignee['addr']) {
                    $this->api_view(false, '请填写配送地址');
                }
                if (!$consignee['mobile'] && !$consignee['telephone']) {
                    $this->api_view(false, '收件人手机和固定电话必须填写一项');
                }
            } else {
                $this->api_view(false, '请填写配送地址信息');
            }
            $ship = $import_data['address_id'];
            #检测是不是货到付款
            if ($post['is_cod'] == 'true' || $post['is_cod'] == 'false') {
                $is_code = $post['is_cod'];
            }
            $shipping = array();
            if ($ship) {
                $shipping = array(
                    'shipping_name' => '快递',
                    'cost_shipping' => $post['cost_shipping'],
                    'is_protect' => 'false',
                    'cost_protect' => 0,
                    'is_cod' => $is_code ? $is_code : 'false'
                );
            } else {
                $this->api_view(false, '请选择物流信息');
            }
            $iorder = $post['order'];
            $iorder['consignee'] = $consignee;
            $iorder['shipping'] = $shipping;
            if ($post['shop_id']) {
                $shop = explode('*', $post['shop_id']);
                $iorder['shop_id'] = $shop[0];
                $iorder['shop_type'] = $shop[1];
                $sObj = $this->app->model("shop");
                $iorder_shop = $sObj->getRow(array('shop_bn' => $iorder['shop_id']));
                if (empty($iorder_shop)) {
                    $this->api_view(false, '请输入正确店铺编号！');
                }

                //add by ldward 20180406 判断店铺状态是否禁用，如果禁用则导入失败【0启用1禁用】
                if($iorder_shop['shopstatus']==2)
                {
                    $this->api_view(false, $post['shop_id'].'店铺已停用，请联系对接人！');
                }
                
                $iorder['shop_id'] = $iorder_shop['shop_id'];
                $iorder['shop_type'] = $iorder_shop['shop_type'];
            } else {
                $this->api_view(false, '请选择来源店铺！');
            }
            //检查关联订单
            $iorder_bn = $oObj->getRow(array('relate_order_bn' => $post['relate_order_bn']));
            if (!empty($iorder_bn)) {
                $this->api_view(false, '关联订单号已存在！');
            }
            //读取商品信息，组合数据
            $num = $post['goods'];
            if (!$num)
                $this->api_view(false, '请选择商品');
            foreach ($num as $k => $v) {
                if ($v['price'] < 0) {
                    $this->api_view(false, '请填写正确的价格');
                }
                if ($v['num'] < 0) {
                    $this->api_view(false, '数量必须大于1');
                }
                $salesMInfo = $salesMLib->getSalesMByBn($iorder['shop_id'], $v['bn']);
                if ($salesMInfo) {
                    //获取绑定的基础物料
                    $basicMInfos = $salesMLib->getBasicMBySalesMId($salesMInfo['sm_id']);
                    $obj_number = $v['num'];
                    $obj_price = $v['price'];
                    //如果是促销类销售物料
                    if ($salesMInfo['sales_material_type'] == 2) {
                        $obj_type = 'pkg';
                        $obj_sale_price = $obj_price * $obj_number;
                        //item层关联基础物料平摊销售价
                        $salesMLib->calProSaleMPriceByRate($obj_sale_price, $basicMInfos);

                        foreach ($basicMInfos as $kk => $basicMInfo) {
                            $order_items[] = array(
                                'product_id' => $basicMInfo['bm_id'],
                                'bn' => $basicMInfo['material_bn'],
                                'name' => $basicMInfo['material_name'],
                                'price' => $basicMInfo['rate_price'] ? bcdiv($basicMInfo['rate_price'], $basicMInfo['number'] * $obj_number, 2) : 0.00,
                                'amount' => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                'sale_price' => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                'quantity' => $basicMInfo['number'] * $obj_number,
                                'sendnum' => 0,
                                'item_type' => 'pkg'
                            );

                            $weight += $basicMInfo['weight'] * $basicMInfo['number'] * $obj_number;
                        }
                    } else {
                        $obj_type = ($salesMInfo['sales_material_type'] == 1) ? 'goods' : 'gift';
                        $item_type = ($obj_type == 'goods') ? 'product' : 'gift';

                        if ($obj_type == 'gift') {
                            $obj_price = 0.00;
                        }

                        foreach ($basicMInfos as $kk => $basicMInfo) {
                            $order_items[] = array(
                                'product_id' => $basicMInfo['bm_id'],
                                'bn' => $basicMInfo['material_bn'],
                                'name' => $basicMInfo['material_name'],
                                'price' => $obj_price,
                                'amount' => $obj_price * $obj_number,
                                'sale_price' => $obj_price * $obj_number,
                                'quantity' => $basicMInfo['number'] * $obj_number,
                                'sendnum' => 0,
                                'item_type' => $item_type
                            );

                            $weight += $basicMInfo['weight'] * $basicMInfo['number'] * $obj_number;
                        }
                    }

                    $iorder['order_objects'][] = array(
                        'obj_type' => $obj_type,
                        'obj_alias' => $obj_type,
                        'goods_id' => $salesMInfo['sm_id'],
                        'bn' => $salesMInfo['sales_material_bn'],
                        'name' => $salesMInfo['sales_material_name'],
                        'price' => $v['price'],
                        'sale_price' => $v['price'] * $obj_number,
                        'amount' => $v['price'] * $obj_number,
                        'quantity' => $obj_number,
                        'order_items' => $order_items
                    );

                    $item_cost += $v['price'] * $obj_number;
                    unset($order_items);
                } else {
                    $this->api_view(false, '店铺无对应物料信息：' . $v['bn']);
                }
            }

            if ($post['customer_memo']) {
                $c_memo = htmlspecialchars($post['customer_memo']);
                $c_memo = array('op_name' => kernel::single('desktop_user')->get_name(), 'op_time' => date('Y-m-d H:i', time()), 'op_content' => $c_memo);
                $tmp[] = $c_memo;
                $iorder['custom_mark'] = serialize($tmp);
                $tmp = null;
            }
            if ($post['order_memo']) {
                $o_memo = htmlspecialchars($post['order_memo']);
                $o_memo = array('op_name' => kernel::single('desktop_user')->get_name(), 'op_time' => date('Y-m-d H:i', time()), 'op_content' => $o_memo);
                $tmp[] = $o_memo;
                $iorder['mark_text'] = serialize($tmp);
                $tmp = null;
            }


            $mathLib = kernel::single('eccommon_math');

            $iorder['member_id'] = $post['member_id'];
            $iorder['weight'] = $weight;
            $iorder['title'] = $p['bn'] . $p['name'];
            $iorder['itemnum'] = count($iorder['order_objects']);
            $iorder['createtime'] = time();
            $iorder['ip'] = $_SERVER['REMOTE_ADDR'];
            $iorder['cost_item'] = $item_cost;
            $iorder['currency'] = 'CNY';
            $iorder['pmt_order'] = $post['pmt_order'];
            $iorder['discount'] = $post['discount'];
            $iorder['relate_order_bn'] = $post['relate_order_bn'];
            $iorder['total_amount'] = $mathLib->number_plus(array($item_cost, $post['cost_shipping'], $post['discount']));
            $iorder['total_amount'] = $mathLib->number_minus(array($iorder['total_amount'], $post['pmt_order']));
            // $iorder['total_amount'] = $item_cost+$post['cost_shipping']-$post['pmt_order']+$post['discount'];

            $iorder['is_delivery'] = 'Y';
            $iorder['source'] = 'local'; //订单来源标识，local为本地新建订单
            $iorder['createway'] = 'local';

            $iorder['pay_status'] = '1';
            $iorder['payed'] = $iorder['total_amount'];

            #新建订单时，要开票的
            if ($post['is_tax'] == 'true') {
                $iorder['is_tax'] = $post['is_tax'];
                $iorder['tax_title'] = $post['tax_title'];
            }

            if ($iorder['total_amount'] < 0)
                $this->api_view(false, '订单金额不能小于0');

            $iorder['order_bn'] = $oObj->gen_id();
            $iorder['download_time'] = time();

            //设置订单失败时间
            $iorder['order_limit_time'] = time() + 60 * (app::get('ome')->getConf('ome.order.failtime'));

            $oObj->create_order($iorder);
            #货到付款类型订单，增加应收金额
            if ($is_code == 'true') {
                $oObj_orextend = $this->app->model("order_extend");
                $code_data = array('order_id' => $iorder['order_id'], 'receivable' => $iorder['total_amount'], 'sellermemberid' => $iorder['member_id']);
                $oObj_orextend->save($code_data);
            }
        }

        $this->api_view(true, '创建成功');
    }

    function order_status()
    {

        $oObj = $this->app->model("orders");


        $datas = $_POST['api_data'];
        $datas = json_decode($datas, true);

        $oObj = $this->app->model("orders");

        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, 'token不正确');
        }
//        $datas['shop_id'] = 'dc5c7986daef50c1e02ab09b442ee34f';
//        $datas['order_bn'] = 12000001;
        $order_status = $oObj->getOrdersByRelateBn($datas['shop_id'], $datas['order_bn']);

        if ($order_status) {
            $this->api_view(true, $order_status);
        } else {
            $this->api_view(false, '无订单数据');
        }
    }

    function order_dead()
    {
        $oObj = $this->app->model("orders");

        $datas = $_POST['api_data'];
        $datas = json_decode($datas, true);

        $oObj = $this->app->model("orders");

        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, 'token不正确');
        }
        $order_status = $oObj->getOrdersByRelateBn($datas['shop_id'], $datas['order_bn'], true);

        if ($order_status) {
            $order_res = $oObj->cancel($order_status['order_id'], 'api更新', true, 'async');

            if ($order_res['rsp'] == 'success') {
                $this->api_view(true, '订单取消成功');
            } else {
                $this->api_view(false, $order_res['msg']);
            }
        } else {
            $this->api_view(false, '无订单数据');
        }
    }

    function material_add()
    {

        $datas = $_POST['api_data'];
        $datas = json_decode($datas, true);

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');
        $basicMaterialConfObjSpe = app::get('material')->model('basic_material_conf_special');
        $barocdeObj = app::get('material')->model('barcode');

        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, 'token不正确');
        }
        if (!$datas) {
            $this->api_view(false, '物料信息不能为空');
        }

        foreach ($datas as $key => $data_val) {

            if (!$this->checkAddParams($data_val, $err_msg)) {
                $this->api_view(false, $err_msg . $data_val['material_name']);
            }

            #检验保质期监控配置
            $use_expire = intval($data_val['use_expire']);
            $warn_day = intval($data_val['warn_day']);
            $quit_day = intval($data_val['quit_day']);
            if ($use_expire == 1 && ($warn_day <= $quit_day)) {
                $this->api_view(false, '预警天数必须大于自动退出库存天数' . $data_val['material_name']);
            }

            // 特殊扫码验证
            if ($data_val['special_setting'] == '3') {
                if (!is_numeric($data_val['first_num']) || !is_numeric($data_val['last_num'])) {
                    $this->api_view(false, '必须输入数字' . $data_val['material_name']);
                }

                #条码的后一个数必须大于前一个
                if ($data_val['last_num'] - $data_val['first_num'] <= 0) {
                    $this->api_view(false, '读取的条码字符顺序错误，前一个框数字必须小于后一个框' . $data_val['material_name']);
                }

                // 扫码的位数长度要等于输入的条码长度
                $code_len = strlen($data_val['material_code']);
                $scan_len = $data_val['last_num'] - $data_val['first_num'] + 1;
                if ($code_len - $scan_len != 0) {
                    $this->api_view(false, '条码长度与扫码配置长度不相等' . $data_val['material_name']);
                }
            }


            //保存物料主表信息
            $addData = array(
                'material_name' => $data_val['material_name'],
                'material_bn' => $data_val['material_bn'],
                'material_bn_crc32' => $data_val['material_bn_crc32'],
                'type' => $data_val['type'],
                'serial_number' => $data_val['serial_number'],
                'visibled' => $data_val['visibled'],
                'create_time' => time(),
            );
            $is_save = $basicMaterialObj->save($addData);

            if ($is_save) {

                //保存条码信息
                $sdf = array(
                    'bm_id' => $addData['bm_id'],
                    'type' => material_codebase::getBarcodeType(),
                    'code' => $data_val['material_code'],
                );
                $barocdeObj->insert($sdf);

                //保存保质期配置
                $useExpireConfData = array(
                    'bm_id' => $addData['bm_id'],
                    'use_expire' => $data_val['use_expire'] == 1 ? 1 : 2,
                    'warn_day' => $data_val['warn_day'] ? $data_val['warn_day'] : 0,
                    'quit_day' => $data_val['quit_day'] ? $data_val['quit_day'] : 0,
                    'create_time' => time(),
                );
                $basicMaterialConfObj->save($useExpireConfData);

                //如果是组合物料保存相关数据
                if ($addData['type'] == 2) {
                    $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');
                    foreach ($data_val['at'] as $k => $v) {
                        $tmpChildMaterialInfo = $basicMaterialObj->dump($k, 'material_name,material_bn');

                        $addCombinationData = array(
                            'pbm_id' => $addData['bm_id'],
                            'bm_id' => $k,
                            'material_num' => $v,
                            'material_name' => $tmpChildMaterialInfo['material_name'],
                            'material_bn' => $tmpChildMaterialInfo['material_bn'],
                            'material_bn_crc32' => sprintf('%u', crc32($tmpChildMaterialInfo['material_bn'])),
                        );
                        $basicMaterialCombinationItemsObj->insert($addCombinationData);
                        $addCombinationData = null;
                    }
                }

                //保存基础物料的关联的特性
                if ($data_val['ftgp_id']) {
                    $addBindFeatureData = array(
                        'bm_id' => $addData['bm_id'],
                        'feature_group_id' => $data_val['ftgp_id'],
                    );
                    $basicMaterialFeatureGrpObj->insert($addBindFeatureData);
                    $addBindFeatureData = null;
                }

                //保存物料扩展信息
                $addExtData = array(
                    'bm_id' => $addData['bm_id'],
                    'cost' => $data_val['cost'] ? $data_val['cost'] : 0.00,
                    'retail_price' => $data_val['retail_price'] ? $data_val['retail_price'] : 0.00,
                    'weight' => $data_val['weight'] ? $data_val['weight'] : 0.00,
                    'unit' => $data_val['unit'],
                    'specifications' => $data_val['material_specification'],
                    'brand_id' => empty($data_val['brand']) ? 0 : $data_val['brand'],
                    'cat_id' => empty($data_val['goods_type']) ? '' : $data_val['goods_type'],
                );
                $basicMaterialExtObj->insert($addExtData);

                //保存物料库存信息
                $addStockData = array(
                    'bm_id' => $addData['bm_id'],
                    'store' => $data_val['store'] ? $data_val['store'] : 0,
                    'store_freeze' => $data_val['store_freeze'] ? $data_val['store_freeze'] : 0,
                );
                $basicMaterialStockObj->insert($addStockData);

                //保存特殊扫码配置信息
                $addScanConfInfo = array(
                    'bm_id' => $addData['bm_id'],
                    'openscan' => $data_val['special_setting'] ? $data_val['special_setting'] : "",
                    'fromposition' => $data_val['first_num'] ? $data_val['first_num'] : "",
                    'toposition' => $data_val['last_num'] ? $data_val['last_num'] : "",
                );
                $basicMaterialConfObjSpe->insert($addScanConfInfo);


            } else {
                $this->api_view(false, '物料同步失败' . $data_val['material_name']);
            }
        }
        $this->api_view(true, '物料同步成功');
    }

    /**
     * 基础物料新增时的参数检查方法
     *
     * @param Array $params
     * @param String $err_msg
     * @return Boolean
     */
    function checkAddParams(&$params, &$err_msg)
    {

        //检查物料名称
        if (empty($params['material_name']) || empty($params['material_bn'])) {
            $err_msg = "必填信息不能为空";
            return false;
        }

        //判断物料编码和物料条码只能是由数字英文下划线组成
        $reg_bn_code = "/^[0-9a-zA-Z\_]*$/";
        if (!preg_match($reg_bn_code, $params["material_bn"])) {
            $err_msg = "物料编码只能是数字英文下划线组成";
            return false;
        }
        if (!preg_match($reg_bn_code, $params["material_code"])) {
            $err_msg = "物料条码只能是数字英文下划线组成";
            return false;
        }

        //检查物料编号
        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialInfo = $basicMaterialObj->getList('material_bn', array('material_bn' => $params['material_bn']));
        if ($basicMaterialInfo) {
            $err_msg = "当前新增的物料编码已存在，不能重复创建";
            return false;
        }
        //检查物料条码
        $barcode = app::get('material')->model('barcode')->getList('bm_id', array('code' => $params['material_code'], 'type' => material_codebase::getBarcodeType()));
        if ($barcode) {
            $err_msg = "当前新增的物料条码已被使用，不能重复使用";
            return false;
        }

        $params['material_bn_crc32'] = sprintf('%u', crc32($params['material_bn']));

        if ($params['type'] == 2) {
            if (!isset($params['at'])) {
                $err_msg = "组合物料请至少设置一个物料明细内容";
                return false;
            }

            foreach ($params['at'] as $val) {
                if (count($params['at']) == 1) {
                    if ($val < 2) {
                        $err_msg = "只有一种物料时，数量必须大于1";
                        return false;
                    }
                } else {
                    if ($val < 1) {
                        $err_msg = "数量必须大于0";
                        return false;
                    }
                }
            }
        }

        return true;
    }

    //获取已打印未校验的发货单
    function GetStocknoticevalue()
    {

        $datas = $_POST['api_data'];
        $cboitem = $_POST['cboitem'];
        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, $_token);
        }
        if ($datas == 'sumnum') {
            $deliveryObj = app::get('wms')->model('delivery');
            echo $deliveryObj->countNoVerifyDelivery();//校验
        } else if ($datas == 'sumship') {
            $deliveryObj = app::get('wms')->model('delivery');
            echo $deliveryObj->countNoProcessDeliveryBill();//出货
        }
    }

    //获取已打印未校验的发货单
    function PDAToLogin()
    {

        $useraccount = $_POST['useraccount'];
        $pwd = $_POST['pwd'];
        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, $_token);
        }
        $account = app::get('pam')->model('account');
        $accountobj = $account->getList('account_id', array('login_name' => $useraccount, 'login_password' => $pwd), 0, 1);

        echo count($accountobj);
    }

    //通过物流单号进行确认
    function PDATOOMS()
    {

        //$logi_no = '2016090108';
        //$material_no = 'DR3136L0301';
        $logi_no = $_POST['api_data'];
        $material_no = $_POST['material'];
        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        if (!$this->_token($token_key, $token_param, $_token)) {
            $this->api_view(false, $_token);
        }
        //1. 获取到的物流条码判断是否可以校验
        $autohide = array('autohide' => 3000);
        $this->begin('index.php?app=wms&ctl=admin_check');
        $checkType = 'all';

        $dlyCheckLib = kernel::single('wms_delivery_check');
        list($usec, $sec) = explode(" ", microtime());
        unset($sec);

        $check_result = $dlyCheckLib->checkAllow($logi_no, $msg, $checkType, true);
        list($usec, $sec) = explode(" ", microtime());
        unset($sec);

        if (!$check_result) {
            echo $msg;
        } else {
            //2. 确认动作

            $dlyItemsModel = app::get('wms')->model('delivery_items');
            $dlyBillObj = kernel::single('wms_delivery_bill');
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            $delivery_id = $dlyBillObj->getDeliveryIdByPrimaryLogi($logi_no);
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            //校验物流和物料号
            $material_code = app::get('material')->model('codebase');
            $bm_id = $material_code->dump(array('code' => $material_no), 'bm_id');
            $orders_items = $dlyItemsModel->getList('product_id'
                , array('delivery_id' => $delivery_id, 'product_id' => $bm_id,));
            if (empty($orders_items)) {
                $this->ShowMsg('快递单号和货号不匹配，请检查！');
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            $dlyModel = app::get('wms')->model('delivery');

            $dly_list = $dlyModel->dump($delivery_id, '*');

            list($usec, $sec) = explode(" ", microtime());
            unset($sec);


            $post_data = array(
                'delivery_id' => $dly_list['delivery_id'],
                'count' => $dly_list['itemNum'],
                'number' => $dly_list['itemNum'],
                'return' => 'OK',
                'checkType' => 'all',
                'logi_no' => $logi_no
            );

            $autohide = array('autohide' => 2000);
            $checkType = in_array($post_data['checkType'], array('barcode', 'all')) ? $post_data['checkType'] : 'barcode';
            //$this->begin();

            if (empty($post_data['delivery_id'])) {
                $this->api_view(false, '发货单ID传入错误', '', $autohide);
            }
            if ($post_data['logi_no'] == '') {
                $this->api_view(false, '请扫描快递单号', '', $autohide);
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            foreach (kernel::servicelist('ome.delivery') as $o) {
                if (method_exists($o, 'pre_docheck')) {
                    $message = "";
                    $result = $o->pre_docheck($post_data, $message);
                    if (!$result) {
                        $this->api_view(false, $message, '', $autohide);
                    }
                }
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            $dly_id = $post_data['delivery_id'];
            $count = $post_data['count'];
            $number = $post_data['number'];
            $logi_no = $post_data['logi_no'];

            //检查订单的当前状态
            $dlyCheckLib = kernel::single('wms_delivery_check');
            if (!$dlyCheckLib->checkOrderStatus($dly_id, true, $errmsg)) {
                $this->api_view(false, $errmsg, '', $autohide);
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            if ($count == 0 || $number == 0) {
                $this->api_view(false, '对不起，校验提交的数据错误', '', $autohide);
            }


            $deliveryObj = app::get('wms')->model('delivery');
            $dly = $deliveryObj->dump($dly_id, '*', array('delivery_items' => array('*')));
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            //检查运单号是否属于同一个处理的发货单
            $deliveryBillLib = kernel::single('wms_delivery_bill');
            $db_logi_no = $deliveryBillLib->getPrimaryLogiNoById($dly_id);
            if ($db_logi_no != $logi_no) {
                $this->ShowMsg('扫描的快递单号与系统中的快递单号不对应');
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            //合计发货单明细的总数
            $total = 0;
            foreach ($dly['delivery_items'] as $i) {
                $total += $i['number'];
            }
            $opObj = app::get('ome')->model('operation_log');
            $deliveryLib = kernel::single('wms_delivery_process');
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            if ($count === $number) {

                //对发货单详情进行校验完成处理
                if ($deliveryLib->verifyDelivery($dly_id)) {
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    if (is_array($post_data['serial_data']) && count($post_data['serial_data']) > 0) {
                        $productSerialObj = app::get('ome')->model('product_serial');
                        $serialLogObj = app::get('ome')->model('product_serial_log');
                        $opInfo = kernel::single('ome_func')->getDesktopUser();

                        #基础物料 ExBOY
                        $basicMStorageLifeLib = kernel::single('material_storagelife');
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        foreach ($post_data['serial_data'] as $key => $val) {
                            foreach ($val as $key_j => $serial) {
                                $serialData['branch_id'] = $dly['branch_id'];
                                $serialData['product_id'] = $post_data['product'][$key];
                                $serialData['bn'] = $key;
                                $serialData['serial_number'] = $serial;
                                $serialData['status'] = 1;

                                #保质期物料_增加保质期条码 ExBOY
                                $is_use_expire = $basicMStorageLifeLib->checkStorageLifeById($serialData['product_id']);
                                if ($is_use_expire) {
                                    $serialData['expire_bn'] = $post_data['expire_data'][$key][$key_j];
                                }

                                $productSerialObj->save($serialData);

                                $logData['item_id'] = $serialData['item_id'];
                                $logData['act_type'] = 0;
                                $logData['act_time'] = time();
                                $logData['act_owner'] = $opInfo['op_id'];
                                $logData['bill_type'] = 0;
                                $logData['bill_no'] = $dly['delivery_id'];
                                $logData['serial_status'] = 1;
                                $serialLogObj->save($logData);
                                unset($serialData, $logData);
                            }
                        }
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                    }

                    //增加发货单校验把保存后的扩展
                    foreach (kernel::servicelist('ome.delivery') as $o) {
                        if (method_exists($o, 'after_docheck')) {
                            $data = $post_data;
                            $o->after_docheck($data);
                        }
                    }
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    //$this->ShowMsg('');
                    $deliveryObj = app::get('wms')->model('delivery');
                    $this->ShowMsg('校验成功|' . $deliveryObj->countNoVerifyDelivery());
                } else {
                    $this->ShowMsg('发货单校验未完成，请重新校验');
                }
            } else {
                list($usec, $sec) = explode(" ", microtime());
                unset($sec);

                //保存部分校验结果
                $flag = $deliveryLib->verifyItemsByDeliveryIdFromPost($dly_id);
                list($usec, $sec) = explode(" ", microtime());
                unset($sec);

                if ($flag) {
                    $opObj->write_log('delivery_check@wms', $dly_id, '发货单部分检验数据保存完成');
                    $this->ShowMsg('发货单部分检验数据保存完成');
                } else {
                    $this->ShowMsg('发货单校验未完成，请重新校验');
                }
            }
        }
    }

    function ShowMsg($msg)
    {
        print_r($msg);
        exit;
    }

    //批量发货
    function PDATOOMSship()
    {
        $token_param = 'ome_admin_api';
        $token_key = 'ax';
        $_token = $_POST['_token'];
        //if(!$this->_token($token_key, $token_param, $_token)){
        //    $this->api_view(false, $_token);
        //}
        $logi_no = $_POST['api_data'];//多批次
        $carno = $_POST['carno'];//车牌号
        $weight = $_POST['weight'];

        if (empty($carno)) {
            $this->ShowMsg('发货失败,车牌号为空！');
        }

        kernel::log('1.0ldward-- begin ship');
        kernel::log("车牌：" . $carno);

        $dlyObj = app::get('wms')->model('delivery');
        $dlyBillObj = app::get('wms')->model('delivery_bill');
        $deliveryBillLib = kernel::single('wms_delivery_bill');
        $opObj = app::get('ome')->model('operation_log');
        $wmsCommonLib = kernel::single('wms_common');
        $dlyProcessLib = kernel::single('wms_delivery_process');
        $orderObj = app::get('ome')->model('orders');
        $omeExtOrdLib = kernel::single('ome_extint_order');

        $primary = false;
        $secondary = false;
        //如果没有发货单信息，则根据物流单号识别是主单还是次单,并获取相关信息

        list($usec, $sec) = explode(" ", microtime());
        unset($sec);

        $delivery_id = $deliveryBillLib->getDeliveryIdByPrimaryLogi($logi_no);
        list($usec, $sec) = explode(" ", microtime());
        unset($sec);
        $minWeight = app::get('wms')->getConf('wms.delivery.minWeight');

        if (!is_null($delivery_id)) {
            $primary = true;
            $dly = $dlyObj->dump(array('delivery_id' => $delivery_id), '*', array('delivery_items' => array('*')));
            $order_bns = $omeExtOrdLib->getOrderBns($dly['outer_delivery_bn']);
            $pause = $orderObj ->getList('pause',array('order_id'=>array_keys($order_bns)));
            foreach ($pause as $key => $value) {
                if ($value['pause'] == 'true') {
                    $pausebool = true;
                    break;
                }
            }
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);//判断$dly是否存在，不存在提示发货单不存在

            if (!$dly) {
                $this->ShowMsg('该订单不存在');
            }
            //重复出货判断
            if ($dly['status'] == 3 && $dly['process_status'] == 7) {
                $this->ShowMsg($dly['delivery_bn'] . '重复发货！');
            }
            //订单暂停的判断
            if ($dly['status'] == 2 || $pausebool){
                $this->ShowMsg($dly['delivery_bn'] . '订单已暂停');
            }

        } else {
            $delivery_id = $deliveryBillLib->getDeliveryIdBySecondaryLogi($logi_no);
            if (!is_null($delivery_id)) {
                $secondary = true;
                $dly = $dlyObj->dump(array('delivery_id' => $delivery_id), '*', array('delivery_items' => array('*')));
                $order_bns = $omeExtOrdLib->getOrderBns($dly['outer_delivery_bn']);
                $pause = $orderObj ->getList('pause',array('order_id'=>array_keys($order_bns)));
                foreach ($pause as $key => $value) {
                    if ($value['pause'] == 'true') {
                        $pausebool = true;
                        break;
                    }
                }

                list($usec, $sec) = explode(" ", microtime());
                unset($sec);

                //判断$dly是否存在，不存在提示发货单不存在
                if (!$dly) {
                    $this->ShowMsg('该订单不存在');
                }
                //重复发货判断
                if ($dly['status'] == 3 && $dly['process_status'] == 7) {
                    $this->ShowMsg($dly['delivery_bn'] . '重复发货！');
                }
                //订单暂停的判断
                if ($dly['status'] == 2 || $pausebool){
                    $this->ShowMsg($dly['delivery_bn'] . '订单已暂停');
                }
            }

        }
        kernel::log("发货单ID：" . $dly['delivery_id']);
        if($dly['net_weight'] == 0){
            $MaterialExtObj = app::get('material')->model('basic_material');
            $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
            foreach($dly['delivery_items'] as $key => $value){
                $bm_id = $MaterialExtObj->dump(array('material_bn'=>$value['bn']),'bm_id');
                $pkg = $basicMaterialExtObj->dump(array('bm_id'=>$bm_id['bm_id']),'weight');
                $dly['net_weight']+=$pkg['weight']*$value['number'];
            }
        }
        $weight = $dly['net_weight'] ? $dly['net_weight'] : 0.00;
        $weight = $weight ? $weight : $minWeight;
        $logi_number = $dly['logi_number'];
        $delivery_logi_number = $dly['delivery_logi_number'];

        //检查前端订单是否退款,原有逻辑是否需要?

        //danny_freeze_stock_log
        define('FRST_TRIGGER_OBJECT_TYPE', '发货单：逐单发货');
        define('FRST_TRIGGER_ACTION_TYPE', 'ome_ctl_admin_consign：consign');

        list($usec, $sec) = explode(" ", microtime());
        unset($sec);


        //获取物流费用
        $area = $dly['consignee']['area'];
        $arrArea = explode(':', $area);
        $area_id = $arrArea[2];
        $delivery_cost_actual = $wmsCommonLib->getDeliveryFreight($area_id, $dly['logi_id'], $weight);

        list($usec, $sec) = explode(" ", microtime());
        unset($sec);

        //如果是次物流单号
        if ($secondary) {
            $data = array(
                'status' => '1',
                'weight' => $weight,
                'delivery_cost_actual' => $delivery_cost_actual,
                'delivery_time' => time(),
                'type' => 2,
            );
            $filter = array('logi_no' => $logi_no);
            $dlyBillObj->update($data, $filter);
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            $logstr = '快递单号:' . $logi_no . ' 发货';
            $opObj->write_log('delivery_bill_express@wms', $dly["delivery_id"], $logstr);
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            if (($logi_number == $delivery_logi_number) && $dly['status'] != 3) {
                if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    /*

                    //判断是否调用物流回传接口
                    $Oshop = app::get('ome')->model('shop');
                    $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                        //调用回传物流信息的接口
                        $delivery_bn = $dly['delivery_bn'];
                        $Oome_delivery = app::get('ome')->model('delivery');
                        $Oome_delivery_order = app::get('ome')->model('delivery_order');
                        $Oome_orders = app::get('ome')->model('orders');
                        $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                        $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                        $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                        $order_bn = $ome_orders['relate_order_bn'];
                        $logi_no = $logi_no;
                        $logi_name = $dly['logi_name'];
                        $shop_bn = $shop['shop_bn'];
                        kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                        $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                    }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                        $Oome_delivery = app::get('ome')->model('delivery');
                        $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                        $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                        $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                    }
                    */

                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    //修改OMS订单字段备货批号
                    $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");
                    $msgss = '发货处理完成';
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    //$deliveryObj  = app::get('wms')->model('delivery');
                    $count = $dlyObj->countNoProcessDeliveryBill();
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    $this->ShowMsg('发货处理完成|' . $count);

                } else {
                    $msg['delivery_bn'] = $dly['delivery_bn'];
                    $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                }
            } else {
                $data = array('delivery_logi_number' => $delivery_logi_number + 1, 'weight' => $dly['weight'] + $weight, 'delivery_cost_actual' => $dly['delivery_cost_actual'] + $delivery_cost_actual);
                $filter = array('delivery_id' => $dly['delivery_id']);
                $dlyObj->update($data, $filter);
                list($usec, $sec) = explode(" ", microtime());
                unset($sec);

                if ($logi_number == ($delivery_logi_number + 1)) {
                    if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        /*
                        //判断是否调用物流回传接口
                        $Oshop = app::get('ome')->model('shop');
                        $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                            //调用回传物流信息的接口
                            $delivery_bn = $dly['delivery_bn'];
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $Oome_delivery_order = app::get('ome')->model('delivery_order');
                            $Oome_orders = app::get('ome')->model('orders');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                            $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                            $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                            $order_bn = $ome_orders['relate_order_bn'];
                            $logi_no = $logi_no;
                            $logi_name = $dly['logi_name'];
                            $shop_bn = $shop['shop_bn'];
                            kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                            $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        */
                        $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");
                        $msgss = '发货处理完成';
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        //$deliveryObj  = app::get('wms')->model('delivery');
                        $count = $dlyObj->countNoProcessDeliveryBill();
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        $this->ShowMsg('发货处理完成|' . $count);

                    } else {
                        $msg['delivery_bn'] = $dly['delivery_bn'];
                        $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                    }
                } else {
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);
                    /*
                    //判断是否调用物流回传接口
                    $Oshop = app::get('ome')->model('shop');
                    $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,is_sendshop');
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                        //调用回传物流信息的接口
                        $delivery_bn = $dly['delivery_bn'];
                        $Oome_delivery = app::get('ome')->model('delivery');
                        $Oome_delivery_order = app::get('ome')->model('delivery_order');
                        $Oome_orders = app::get('ome')->model('orders');
                        $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                        $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                        $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                        $order_bn = $ome_orders['relate_order_bn'];
                        $logi_no = $logi_no;
                        $logi_name = $dly['logi_name'];
                        kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($delivery_bn, $order_bn, $logi_no, $logi_name);
                        $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                    }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                        $Oome_delivery = app::get('ome')->model('delivery');
                        $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                        $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                        $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                    }
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);
                    */
                    $this->ShowMsg('发货处理完成|' . $dlyObj->countNoProcessDeliveryBill());
                }
            }
        } else {
            list($usec, $sec) = explode(" ", microtime());
            unset($sec);

            //判断这个主物流单有没有对应的次物流单,等于1的时候只有一个包裹单
            if ($logi_number == 1) {
                if (($logi_number == $delivery_logi_number) && $dly['status'] != 3) {
                    if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        /*
                        //判断是否调用物流回传接口
                        $Oshop = app::get('ome')->model('shop');
                        $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                            //调用回传物流信息的接口
                            $delivery_bn = $dly['delivery_bn'];
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $Oome_delivery_order = app::get('ome')->model('delivery_order');
                            $Oome_orders = app::get('ome')->model('orders');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                            $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                            $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                            $order_bn = $ome_orders['relate_order_bn'];
                            $logi_no = $logi_no;
                            $logi_name = $dly['logi_name'];
                            $shop_bn = $shop['shop_bn'];
                            kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                            $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        */
                        $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        //$deliveryObj  = app::get('wms')->model('delivery');
                        $count = $dlyObj->countNoProcessDeliveryBill();
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        $this->ShowMsg('发货处理完成|' . $count);

                    } else {
                        $msg['delivery_bn'] = $dly['delivery_bn'];
                        $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                    }
                } else {
                    $data = array(
                        'status' => '1',
                        'weight' => $weight,
                        'delivery_cost_actual' => $delivery_cost_actual,
                        'delivery_time' => time(),
                        'type' => 1,
                    );
                    $filter = array('logi_no' => $logi_no);
                    $dlyBillObj->update($data, $filter);
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    $data = array('delivery_logi_number' => $delivery_logi_number + 1, 'weight' => $dly['weight'] + $weight, 'delivery_cost_actual' => $dly['delivery_cost_actual'] + $delivery_cost_actual);
                    $filter = array('delivery_id' => $dly['delivery_id']);
                    $dlyObj->update($data, $filter);
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        //判断是否调用物流回传接口
                        $Oshop = app::get('ome')->model('shop');
                        $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                        ob_start();
                        $out1 = ob_get_contents();

                        ob_end_clean();
                        ob_end_flush();
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        /*
                        if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                            //调用回传物流信息的接口
                            $delivery_bn = $dly['delivery_bn'];
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $Oome_delivery_order = app::get('ome')->model('delivery_order');
                            $Oome_orders = app::get('ome')->model('orders');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                            $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                            $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                            $order_bn = $ome_orders['relate_order_bn'];
                            $logi_no = $logi_no;
                            $logi_name = $dly['logi_name'];
                            $shop_bn = $shop['shop_bn'];
                            kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                            $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                            $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                        }
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        */
                        $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        //$deliveryObj  = app::get('wms')->model('delivery');
                        $count = $dlyObj->countNoProcessDeliveryBill();

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        $this->ShowMsg('发货处理完成|' . $count);

                    } else {
                        $msg['delivery_bn'] = $dly['delivery_bn'];
                        $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                    }
                }
            } else {
                //如果存在子物流单
                //计算已经发货的子物流单、总共的物流单
                //1,查询实际的发货数量，和总物流数量
                if (($logi_number > $delivery_logi_number)) {
                    $data = array(
                        'status' => '1',
                        'weight' => $weight,
                        'delivery_cost_actual' => $delivery_cost_actual,
                        'delivery_time' => time(),
                        'type' => 1,
                    );
                    $filter = array('logi_no' => $logi_no);
                    $dlyBillObj->update($data, $filter);
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    $data = array(
                        'delivery_logi_number' => $delivery_logi_number + 1,
                        'weight' => $dly['weight'] + $weight,
                        'delivery_cost_actual' => $dly['delivery_cost_actual'] + $delivery_cost_actual,
                    );
                    $filter = array('delivery_id' => $dly['delivery_id']);
                    $dlyObj->update($data, $filter);
                    list($usec, $sec) = explode(" ", microtime());
                    unset($sec);

                    if ($logi_number == ($delivery_logi_number + 1)) {
                        if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {
                            list($usec, $sec) = explode(" ", microtime());
                            unset($sec);
                            /*
                            //判断是否调用物流回传接口
                            $Oshop = app::get('ome')->model('shop');
                            $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                            list($usec, $sec) = explode(" ", microtime());
                            unset($sec);

                            if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                                //调用回传物流信息的接口
                                $delivery_bn = $dly['delivery_bn'];
                                $Oome_delivery = app::get('ome')->model('delivery');
                                $Oome_delivery_order = app::get('ome')->model('delivery_order');
                                $Oome_orders = app::get('ome')->model('orders');
                                $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                                $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                                $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                                $order_bn = $ome_orders['relate_order_bn'];
                                $logi_no = $logi_no;
                                $logi_name = $dly['logi_name'];
                                $shop_bn = $shop['shop_bn'];
                                kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                                $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                            }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                                $Oome_delivery = app::get('ome')->model('delivery');
                                $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                                $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                                $dlyObj->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                            }
                            list($usec, $sec) = explode(" ", microtime());
                            unset($sec);
                            */
                            $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");

                            list($usec, $sec) = explode(" ", microtime());
                            unset($sec);

                            //$deliveryObj  = app::get('wms')->model('delivery');
                            $count = $dlyObj->countNoProcessDeliveryBill();

                            list($usec, $sec) = explode(" ", microtime());
                            unset($sec);

                            $this->ShowMsg('发货处理完成|' . $count);
                        } else {
                            $msg['delivery_bn'] = $dly['delivery_bn'];
                            $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                        }
                    }
                    //加入如果$logi_number==$delivery_logi_number 但是发货状态没有改变的判断
                } elseif (($delivery_logi_number == $logi_number) && $dly['status'] != 3) {
                    if ($dlyProcessLib->consignDelivery($dly['delivery_id'])) {
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        /*
                        //判断是否调用物流回传接口
                        $Oshop = app::get('ome')->model('shop');
                        $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']), 'isWD,shop_bn,is_sendshop');
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        if ($shop['isWD'] == 'true' && $shop['is_sendshop'] == 'true') {
                            //调用回传物流信息的接口
                            $delivery_bn = $dly['delivery_bn'];
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $Oome_delivery_order = app::get('ome')->model('delivery_order');
                            $Oome_orders = app::get('ome')->model('orders');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']), 'delivery_id');
                            $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']), 'order_id');
                            $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']), 'relate_order_bn');
                            $order_bn = $ome_orders['relate_order_bn'];
                            $logi_no = $logi_no;
                            $logi_name = $dly['logi_name'];
                            $shop_bn = $shop['shop_bn'];
                            kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop_bn, $delivery_bn, $order_bn, $logi_no, $logi_name);
                        }elseif($shop['isWD'] == 'false' && $shop['is_sendshop'] == 'true'){
                            $Oome_delivery = app::get('ome')->model('delivery');
                            $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                            $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                        }
                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);
                        */
                        $dlyObj->db->exec("update sdb_wms_delivery set carno = '" . $carno . "' where  delivery_id in(" . $dly['delivery_id'] . ")");

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        //$deliveryObj  = app::get('wms')->model('delivery');
                        $count = $dlyObj->countNoProcessDeliveryBill();

                        list($usec, $sec) = explode(" ", microtime());
                        unset($sec);

                        $this->ShowMsg('发货处理完成|' . $count);
                    } else {
                        $msg['delivery_bn'] = $dly['delivery_bn'];
                        $this->ShowMsg($msg['delivery_bn'] . '发货未完成');
                    }
                } else {
                    $this->ShowMsg('此物流运单已发货');
                }
            }
        }
    }

    /**
     * 加入队列  自动确认和发货
     * $_POST['api_data'] = "70276102440183,70276102440184,70276102440185";
     * $_POST['carno'] = "A98760";
     */
    function PDATOOMSbatchCheckAndDelivery()
    {
        $logi_no = $_REQUEST['api_data'];
        $carno = $_REQUEST['carno'];//车牌号
        $weight = $_REQUEST['weight'] ? $_REQUEST['weight'] : 0;

        $ids = $logi_no;  //多批次
        $delivery_ids = explode(',', $ids);
        $delivery_ids = array_filter($delivery_ids);
        $logi_nums = array_unique($delivery_ids);

        if (empty($carno)) {
            $this->ShowMsg('加入队列失败,车牌号为空！');
        }

        if ( !$delivery_ids ) {
            $this->ShowMsg('快递单列表不能为空！');
        }

        $batch_number = count($delivery_ids);
        $blObj = app::get('wms')->model('batch_log');

        $bldata = array(
            'op_id' => 16777215, //kernel::single('desktop_user')->get_id(),
            'op_name' => 'system', //kernel::single('desktop_user')->get_name(),
            'createtime' => time(),
            'batch_number' => $batch_number,
            'log_type' => 'checkandconsign',
//            'log_text'=>serialize($logi_nums),
            'log_text'=>serialize(array(
                'logi_no' => $logi_nums,
                'carno' => $carno,
            )),
        );
        $result = $blObj->save($bldata);

        //校验任务加队列
        $push_params = array(
            'data' => array(
                'log_text' => $bldata['log_text'],
                'log_id' => $bldata['log_id'],
                'task_type' => 'autochkanddly'
            ),
            'url' => kernel::openapi_url('openapi.autotask', 'service')
        );
	$res=kernel::single('taskmgr_interface_connecter')->push($push_params);
	if($res){
	    $this->ShowMsg('已提交至队列！');
	}else{
            $this->ShowMsg('提交队列失败！');
	}
    }

    /**
     * @param $arritems
     * @param $carno
     * @return string
     */
    function batchGetLogicNo($arritems, $carno)
    {
        $result = '';
        $xml = '';
        $listshipdocno = array();
        kernel::log('3.0ldward-- start ax');
        foreach ($arritems as $key => $value) {
            $dlyBillObj = app::get('wms')->model('delivery_items');
            $deliveryBillLib = kernel::single('wms_delivery_bill');
            $delivery_id = $deliveryBillLib->getDeliveryIdByPrimaryLogi($value);
            $dlyitems = $dlyBillObj->getList('shipdocno', array('delivery_id' => $delivery_id));

            foreach ($dlyitems as $key => $value1) {
                if (!empty($value1['shipdocno'])) {
                    if (!in_array($value1['shipdocno'], $listshipdocno)) {
                        array_push($listshipdocno, $value1['shipdocno']);
                        $xml .= '<HV_WMSFGPickingRoute>'
                            . '<fgpickingRouteID>' . $value1['shipdocno']
                            . '</fgpickingRouteID><LicencePlateNo>' . $carno
                            . '</LicencePlateNo></HV_WMSFGPickingRoute>';
                    }
                    //$result=$this->DoPDAShip($value1['shipdocno']);
                }
            }
        }
        if ($xml) {
            $xml = "<?xml version='1.0' encoding='UTF-8'?><HV_WMSFGPickingRouteGroup>" . $xml . "</HV_WMSFGPickingRouteGroup>";
            kernel::log('3.0ldward--' . $xml);
            $action = 'CreatePickingRoute';

            $response = $this->HttpSoap(WEBSERVICE_DOMAIN, WEBSERVICE_POST, '/AXToOMs.asmx', 'http://tempuri.org/', $action, $xml);
            $p = xml_parser_create();
            xml_parse_into_struct($p, $response, $vals, $index);
            xml_parser_free($p);

            $respxml = '';
            if ($vals) {
                foreach ($vals as $v) {
                    if ($v['tag'] == 'CREATEPICKINGROUTERESULT') {
                        $res = true;
                        $respxml = $v['value'];
                        break;
                    }
                }
            }
            if (strpos($respxml, 'error:') === 0) {
                var_dump($respxml);
            }
            $result = '';
            if (!empty($respxml)) {
                $doc = new DOMDocument();
                $doc->loadXML($respxml);

                $items = $doc->getElementsByTagName('CustPackingSlipJourGroup');
                foreach ($items as $key => $val) {
                    $CustPackingSlipJour = $val->getElementsByTagName("CustPackingSlipJour")->item(0)->nodeValue;
                    if ($CustPackingSlipJour != '') {
                        $result = $CustPackingSlipJour;
                    }
                }
            }
        }
        return $result;
    }

    /**
     *  soap
     * @param type $server
     * @param type $port
     * @param type $url
     * @param type $namespace
     * @param type $action
     * @param type $data
     * @return type
     */
    function HttpSoap($server, $port, $url, $namespace, $action, $data)
    {
        $fp = @fsockopen($server, $port);
        if (!$fp) {
            return "Don't have access to this web site";
        } else {
            $soapData = $this->ConstructData($namespace, $action, $data);

            $length = strlen($soapData);
            $out = "POST $url HTTP/1.1\r\n";
            $out .= "Host: $server\r\n";
            $out .= "Content-Type: application/soap+xml; charset=utf-8\r\n";
            $out .= "Content-Length: $length\r\n\r\n";
//            $out .= "SOAPAction: \"$namespace$action\"\r\n\r\n";
            $out .= $soapData;
            $out .= "\r\n\r\n";
            fputs($fp, $out);
            stream_set_timeout($fp, 20);
            $header = "";
            while ($line = trim(fgets($fp))) {
                $header .= $line . "\n";
            }
            kernel::log($header);
            $length = 8192;
            if ($header) {
                $ll = strpos($header, 'Content-Length:');
                if ($ll !== false) {
                    $length = intval(substr($header, $ll + 15));
                }
            }
            kernel::log($length);
            $data = fread($fp, $length);
            fclose($fp);
            return $data;
        }
    }

    function ConstructData($namespace, $action, $data)
    {

        $data2 = "<?xml version='1.0' encoding='UTF-8'?><HV_WMSFGPickingRouteGroup><HV_WMSFGPickingRoute><fgpickingRouteID>FSN-11201523621</fgpickingRouteID></HV_WMSFGPickingRoute></HV_WMSFGPickingRouteGroup>";

        $data = htmlspecialchars($data);

        if ($action == 'CreateSalesOrder') {
            $soapData = <<<xml
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <CreateSalesOrder xmlns="http://tempuri.org/">
      <str>$data</str>
    </CreateSalesOrder>
  </soap12:Body>
</soap12:Envelope>
xml;
        } elseif ($action == 'CreatePickingRoute') {
            $soapData = <<<xml
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <CreatePickingRoute xmlns="http://tempuri.org/">
      <str>$data</str>
    </CreatePickingRoute>
  </soap12:Body>
</soap12:Envelope>
xml;
        }
        return $soapData;
    }
}
